<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="700px" @ok="handleSubmit" destroyOnClose>
    <MyAlert 
      type="warning"
      message="所有的敏感数据保存之后不会明文展示, 请自己妥善保管"
    />
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, useAttrs } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { commonFromSchema, ConfigPageType } from './payIfConfig.data';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { saveOrUpdatePayConfig } from './payIfConfig.api';
import { ColEx } from '/@/components/Form/src/types';
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
import MyAlert from '/@/components/My/MyAlert.vue';

// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const rowId = ref('');
const payIfConfig = ref<any>()
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, resetSchema, appendSchemaByField }] = useForm({
  layout: 'vertical',
  labelWidth: '100%',
  showActionButtonGroup: false,
  wrapperCol: { lg: 24, md: 24 }
});

//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  console.log("payIfConfig: ", data.record);
  
  let showFooter = data?.showFooter ?? true
  setDrawerProps({ confirmLoading: false, showFooter })
  isUpdate.value = !!data?.isUpdate;
  payIfConfig.value = data.record.payIfConfig
  const config =  payIfConfig.value
  let schemas: any = []

  // 设置公共表单参数
  schemas.push.apply(schemas, commonFromSchema)
  schemas.push({
    field: config.ifName + "-" + config.mchTypeName + '-divider',
    component: 'Divider',
    label: config.ifName + " " + config.mchTypeName + "配置",
  })

  let ifParams = {}
  if (config.configPageType == ConfigPageType.JSON) {
    let configParams: any = []
    if (config.isMchMode == "1" && config.mchParams) {
      // 普通商户
      configParams = JSON.parse(config.mchParams)
    }
    if (configParams) {
      configParams.forEach(e => {
        schemas.push({
          field: e.field,
          label: e.label,
          show: e.show === undefined || e.show ? true : false,
          required: e.required ? e.required : false,
          componentProps: e.componentProps,
          helpMessage: e.helpMessage,
          defaultValue: e.defaultValue,
          component: e.component,
        })
      })
    }
    
    await resetSchema(schemas)
    if (typeof config === 'object') {
      if (!config.ifParams) {
        config.ifParams = '{}'
      }
      try {
        ifParams = JSON.parse(config.ifParams)
      } catch(e) {
        console.error(e);
      }
    }
  } else {
    // 添加自定义页面
    await resetSchema(schemas)
  }
  console.log('form-value: ', { ...ifParams, ...config })
  setFieldsValue({ ...ifParams, ...config })
  setProps({ disabled: !showFooter })
});
//获取标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增支付接口配置' : '编辑支付接口配置'));

//提交事件
async function handleSubmit() {
  try {
    let values = await validate();
    console.log('------------', values)
    setDrawerProps({ confirmLoading: true });
    let submitValues : any= {}
    submitValues.status = values.status
    submitValues.remark = values.remark
    submitValues.id =  payIfConfig.value.id

    for (const key in values) {
      if (key.includes('-divider') || ['status', 'remark', 'id'].indexOf(key) != -1) {
        delete values[key]
      }
    }
    submitValues.ifParams = JSON.stringify(values)
    console.log("submit: ", submitValues);
    
    //提交表单
    await saveOrUpdatePayConfig(submitValues, unref(isUpdate));
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    createMessage.success('配置成功')
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
